import { http } from "@/utils/http";
import { type BaseResponseType, baseUrlApi } from "@/api/types";
import { encryptByRSA } from "@/utils/auth";
/** 获取`RSA公钥` */
export interface RSAKeyResponse extends BaseResponseType {
  publickey: string;
}

/** 用户登录响应 */
export interface LoginResponse extends BaseResponseType {
  tokens: {
    refreshtoken: string;
    token: string;
  };
}

/** 个人信息 */
export interface UserInfo {
  phone: null | string;
  /** 积分 */
  point: number;
  qqnum: null | string;
  /** 课题组 */
  rpgname: null | string;
  /** 单位 */
  unit: string;
  useremail: string;
  username: string;
}
export interface UserInfoResponse extends BaseResponseType {
  myinfo: UserInfo;
}

/** 获取RSA密钥 */
export let getRSAKey = () => {
  return http.get<RSAKeyResponse, void>(baseUrlApi("/publicKey"));
};

/** 用户登录 **/
export let userLogin = (data) => {
  return http.post<LoginResponse, object>(baseUrlApi("/auth/login"), { data });
};

/**获取邮箱验证码方法*/
export async function getEmailCode(data) {
  let { publickey } = await getRSAKey();
  let emaliData = JSON.stringify({ email: data });
  let encryptData = { data: "" };
  encryptData.data = await encryptByRSA(publickey, emaliData);
  return http.post<any, any>(baseUrlApi("/verificationcode/email"), {
    data: JSON.stringify(encryptData),
  });
}

/**用户重置密码*/
export async function userResetPwd(data) {
  let { publickey } = await getRSAKey();
  let emaliData = JSON.stringify(data);
  let encryptData = {
    data: "",
  };
  encryptData.data = await encryptByRSA(publickey, emaliData);
  
  return http.post<any, any>(baseUrlApi("/auth/resetpwd"), {
    data: JSON.stringify(encryptData),
  });
}

/** 刷新token */
export let refreshTokenApi = (data: object) => {
  console.log("发送请求");
  return http.get<LoginResponse, object>(baseUrlApi("/auth/refreshlogin"), {
    params: data,
  });
};

/** 获取用户信息方法 **/
export let getUserInfo = () => {
  return http.get<UserInfoResponse, void>(baseUrlApi("/auth/info"));
};